/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * QueryBuilder.java
 * wholebasic
 * 2014年6月19日上午10:42:05
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.util;

import java.lang.reflect.Field;
import java.util.Map;

import org.jackysoft.entity.nosql.AbstractNoSqlEntity;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

public class MorphiaQueryBuilder {
	
	static final Logger logger = LoggerFactory.getLogger(MorphiaQueryBuilder.class);
	
	public static final <T extends AbstractNoSqlEntity> Query<T> build(T where,
			Query<T> query) {
		
		Class<?> c = where.getClass();

		Field[] fds = c.getFields();
		try {
			for (Field f : fds) {
				if (f.isAnnotationPresent(org.jackysoft.annotations.Query.class)) {
                    query.field(f.getName()).equal(f.get(where));
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			logger.error(e+"");

		}
	    return query;
	}
	
	public static final <T extends AbstractNoSqlEntity> Map<String,Object> buildUpdate(T where) {
		
		Map<String,Object> results = Maps.newHashMap();
		Class<?> c = where.getClass();
		
		Field[] fds = c.getFields();
		try {
			for (Field f : fds) {
				if (!f.isAnnotationPresent(org.jackysoft.annotations.NoUpdate.class) && f.get(where)!=null) {
					results.put(f.getName(), f.get(where));
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			logger.error(e+"");
			
		}
		return results;
	}
}
